//
//  MinePhotosViewController.m
//  MJApp
//
//  Created by scjh on 15/5/13.
//  Copyright (c) 2015年 wangliang. All rights reserved.
//

#import "MinePhotosViewController.h"

#import "MinePhotosCollectionViewCell.h"
#import "RSKImageCropViewController.h"
#import "CamareModel.h"
#import "UIImage+Addition.h"

@interface MinePhotosViewController () <UICollectionViewDataSource, UICollectionViewDelegate,
  UIActionSheetDelegate, UIImagePickerControllerDelegate, RSKImageCropViewControllerDelegate,
  HomeCellDelegate>

@property (weak, nonatomic) IBOutlet UIButton *saveBtn;
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong, nonatomic) UIActionSheet *actionSheet;
@property (assign, nonatomic) NSInteger allNum;
@property (strong, nonatomic) NSMutableArray *imageArray;
@property (assign, nonatomic) NSInteger row;

@property (nonatomic,strong) NSString *deleteID;

@end

@implementation MinePhotosViewController


- (NSMutableArray *)imageArray {
    
    if (!_imageArray) {
        
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}

- (instancetype)initWithOriginArray:(NSArray *)originArray {
    
    self = [super init];
    if (self) {
        [self.imageArray addObjectsFromArray:originArray];
        self.allNum = originArray.count + 1;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self UI];
}

- (void)UI {
    
    self.title = @"相册";
    self.view.backgroundColor = Color_Back_Black;
    self.saveBtn.layer.cornerRadius = CGRectGetHeight(self.saveBtn.frame) / 2;
    self.cancelBtn.layer.cornerRadius = CGRectGetHeight(self.cancelBtn.frame) / 2;
    self.saveBtn.hidden = YES;
    self.cancelBtn.hidden = YES;
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 30, 0, 30);
    flowLayout.itemSize = CGSizeMake(80, 80);
    self.collectionView.collectionViewLayout = flowLayout;
    self.collectionView.scrollEnabled = NO;
    self.collectionView.backgroundColor = Color_Back_Black;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerNib:
    [UINib nibWithNibName:@"MinePhotosCollectionViewCell" bundle:nil]
          forCellWithReuseIdentifier:@"MinePhotosCollectionViewCell"];
    
    self.actionSheet = [[UIActionSheet alloc] initWithTitle:@"添加相片"
                                                   delegate:self
                                          cancelButtonTitle:@"取消"
                                     destructiveButtonTitle:nil
                                          otherButtonTitles:@"相册",@"相机", nil];
}

#pragma mark collectionViewDelegate 

- (NSInteger)collectionView:(UICollectionView *)collectionView
     numberOfItemsInSection:(NSInteger)section {
    
    return self.allNum;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    MinePhotosCollectionViewCell *cell =
        [collectionView dequeueReusableCellWithReuseIdentifier:@"MinePhotosCollectionViewCell"
                                                  forIndexPath:indexPath];
    cell.status = indexPath.row != self.allNum - 1;
    if (cell.status) {
        
        cell.infoDic = @{
        @"image" :self.imageArray[indexPath.row],
        @"index" :@(indexPath.row)
        };
    }else {
        
        cell.infoDic = @{
        @"image" :[UIImage imageNamed:@"grzx_11"],
        @"index" :@(indexPath.row)
        };
    }
    cell.delegate = self;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView
 didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    self.row = indexPath.row;
    [self.actionSheet showInView:self.view];
    
//    self.allNum < 8 ? self.allNum ++ : self.allNum;
//    [self.collectionView reloadData];
}

#pragma mark actionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (actionSheet.tag == 6) {
        
        switch (buttonIndex) {
            case 0:
            {
                NSDictionary *dic = @{@"id":self.deleteID};
                [WLHttpRequestAfter userDelPhotoWithParam:dic usingSucessBlock:^(BOOL isSucess, NSDictionary *resultDictionary) {
                    
                    if ([resultDictionary[@"status"] integerValue] ==1) {
                        
                        [[DMCAlertCenter defaultCenter] postAlertWithMessage:@"图片删除成功"];
                        [self obtaionData];
                    }else {
                        
                        [[DMCAlertCenter defaultCenter] postAlertWithMessage:resultDictionary[@"msg"]];
                    }
                } andFailureBlock:^(NSError *resultError) {
                    
                }];
            }
                break;
            case 1:
            {
                NSLog(@"1");
            }
                break;
            default:
                break;
        }
    }else {
        
        switch (buttonIndex) {
            case 0:
            {
                NSLog(@"0");
                //相册
                [CamareModel camareModelPhotoDelegate:self];
            }
                break;
            case 1:
            {
                NSLog(@"1");
            }
                break;
            default:
                break;
        }
    }
}

#pragma mark uiimagepickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    CGFloat wide = IOS_IPHONE_WINDOW_WIDE * 2;
    CGFloat high = wide * image.size.height / image.size.width;
    UIImage *currImage = [image compressionScaleSize:CGSizeMake(wide, high)];
    RSKImageCropViewController *cropVC =
    [[RSKImageCropViewController alloc] initWithImage:currImage];
    cropVC.delegate = self;
    [picker pushViewController:cropVC animated:YES];
}

#pragma mark RSKImageCropViewControllerDelegate 

- (void)imageCropViewController:(RSKImageCropViewController *)controller
                   didCropImage:(UIImage *)croppedImage {
    
//    if (self.row < self.imageArray.count) {
//        
//        [self.imageArray replaceObjectAtIndex:self.row withObject:croppedImage];
//    }else {
//        
//        [self.imageArray addObject:croppedImage];
//        self.allNum < 8 ? self.allNum ++ : self.allNum;
//    }
//    [self.collectionView reloadData];

    [self addPhoto:croppedImage];
    [controller dismissViewControllerAnimated:YES completion:nil];
}

- (void)imageCropViewControllerDidCancelCrop:(RSKImageCropViewController *)controller {
    
    [controller dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark homeCellDelegate 

- (void)homeCell:(id)cell withInfo:(id)info {
    
    NSInteger index = [info[@"index"] integerValue];
    self.deleteID = [NSString stringWithFormat:@"%@",self.imageArray[index][@"id"]];
    
//    [self.imageArray removeObjectAtIndex:index];
//    self.allNum --;
//    [self.collectionView reloadData];
    
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"确定" otherButtonTitles:nil];
    sheet.tag = 6;
    [sheet showInView:self.view];
}

#pragma mark 保存方法
- (IBAction)saveBtn:(id)sender {
    
    
    for (int i = 0; i < self.imageArray.count; i ++) {
    
        NSDictionary *dic = @{
                              @"user_id":[userInfoTool share].ID,
                              @"type":@"1",
                              @"filename":self.imageArray[i]
                              };
        [WLHttpRequestAfter userModifyHeadWithParam:dic usingSucessBlock:^(BOOL isSucess, NSDictionary *resultDictionary) {
            
            NSLog(@"1111");
        } andFailureBlock:^(NSError *resultError) {
            
        }];

    }
}

- (IBAction)cancelBtn:(id)sender {

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)obtaionData {
    
    NSDictionary *dic = @{@"user_id":[userInfoTool share].ID};
    [WLHttpRequestAfter userCenterInfoWithParam:dic usingSucessBlock:^(BOOL isSucess, NSDictionary *resultDictionary) {
        if ([resultDictionary[@"status"] integerValue] == 1) {
            
            [self.imageArray removeAllObjects];
            NSArray *originArray = resultDictionary[@"data"][@"photo"];
            [self.imageArray addObjectsFromArray:originArray];
            self.allNum = originArray.count + 1;
            [self.collectionView reloadData];
        }else {
            
            [[DMCAlertCenter defaultCenter] postAlertWithMessage:resultDictionary[@"msg"]];
        }
        
    } andFailureBlock:^(NSError *resultError) {
        
    }];
}


- (void)addPhoto:(UIImage *)image {
    
    NSDictionary *dic = @{
                          @"user_id":[userInfoTool share].ID,
                          @"type":@"1",
                          @"filename":image
                          };
    [WLHttpRequestAfter userModifyHeadWithParam:dic usingSucessBlock:^(BOOL isSucess, NSDictionary *resultDictionary) {
        
        if ([resultDictionary[@"status"] integerValue] == 1) {
            
            [self obtaionData];
        }else {
            
            [[DMCAlertCenter defaultCenter] postAlertWithMessage:resultDictionary[@"msg"]];
        }
    } andFailureBlock:^(NSError *resultError) {
        
    }];
}

@end
